
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            Fast.config.openArea = ['95%','95%'];
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'course/coupon/index' + location.search,
                    add_url: 'course/coupon/add',
                    edit_url: 'course/coupon/edit',
                    del_url: 'course/coupon/del',
                    multi_url: 'course/coupon/multi',
                    import_url: 'course/coupon/import',
                    table: 'coupon',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},

                        {field: 'type', title: __('Type'), operate: 'LIKE', searchList: Config.typeList,formatter: Table.api.formatter.label},
                        {field: 'title', title: __('Title'), operate: 'LIKE' ,formatter: Controller.api.formatter.info},
                        // {field: 'discount', title: __('Discount'), operate:'BETWEEN'},
                        // {field: 'money', title: __('Money'), operate:'BETWEEN'},
                        // {field: 'reduction_money', title: __('Reduction_money'), operate:'BETWEEN'},

                        {field: 'num', title: __('Num')},
                        {field: 'surplus_num', title: __('Surplus_num')},

                        // {field: 'store_id', title: __('Store_id')},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        {field: 'switch', title: __('Switch'), searchList: {"1":__('Yes'),"0":__('No')}, table: table, formatter: Table.api.formatter.toggle},

                        // {field: 'store.title', title: __('Store.title'), operate: 'LIKE'},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'send_coupon',
                                    text: function (row){
                                        return __('发放优惠券');
                                    },
                                    title: function (row){
                                        return __('发放优惠券-')+row.title;
                                    },
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'course/coupon/send_coupon',
                                    callback: function (data,ret) {
                                        layer.msg(JSON.stringify(data), {
                                            time: 1000,
                                        });
                                        table.bootstrapTable('refresh');
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                }
                            ],
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        send_coupon: function () {


            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'user/user',
                    send_url: 'course/coupon/send',
                }
            });
            var table = $("#table");
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='tag_ids']", form).addClass("selectpage").data("source", "course/tags/selectpage")
                    .data("primaryKey", "id")
                    .data("field", "name")
                    .data("multiple", true)
                    .data("orderBy", "id desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });
            // 初始化表格
            table.bootstrapTable({
                commonSearch: true,
                search: false, //是否启用快速搜索
                searchFormVisible: true, //是否始终显示搜索表单
                showExport: false,//是否开启导出
                showToggle: false,//开启切换按钮
                showColumns: false,//开启展示字段
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'mobile', title: __('手机号    '), operate: 'LIKE'},
                        {field: 'student_name', title: __('学员名称'),visible: false, operate: 'LIKE'},

                        {field: 'nickname', title: __('Username'),operate: 'LIKE %...%'},
                        {field: 'tag_ids', title: __('Tags'), formatter: Table.api.formatter.search,visible: false},

                        {field: 'tags', title: __('Tags'), operate: false, formatter: Table.api.formatter.flag},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $(document).on("click", "#dispose", function () {

                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                console.log(ids, page, all);
                Layer.confirm("请选择发送优惠券的选项<form ><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'><input type='hidden' name='coupon_id'></form>", {
                    title: '发送优惠券',
                    btn: ["选中项(" + ids.length + "条)", "全部(" + all + "条)"],
                    success: function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");

                    }
                    , yes: function (index, layero) {
                        if(ids.length<=0 ){
                            layer.msg("未选择数据");
                            return
                        }
                        submitForm(ids.join(","), layero);
                        return false;
                    }
                    ,
                    btn2: function (index, layero) {
                        if(all<=0){
                            layer.msg("没有数据");
                            return;
                        }
                        submitForm("all", layero);
                        return false;
                    }
                });
            });

            var submitForm = function (ids, layero) {
                var options = table.bootstrapTable('getOptions');
                // console.log(options);
                // console.log(options.searchText);
                var columns = [];
                $.each(options.columns[0], function (i, j) {
                    if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                        columns.push(j.field);
                    }
                });
                var search = options.queryParams({});
                // console.log(search);
                // $("input[name=search]", layero).val(options.searchText);
                // $("input[name=ids]", layero).val(ids);
                // $("input[name=filter]", layero).val(search.filter);
                // $("input[name=op]", layero).val(search.op);
                // $("input[name=columns]", layero).val(columns.join(','));
                // $("input[name=coupon_id]", layero).val(Config.coupon_id);
                Fast.api.ajax({
                        data:{
                            search:options.searchText,
                            ids:ids,
                            filter:search.filter,
                            op:search.op,
                            columns:columns.join(','),
                            coupon_id:Config.coupon_id,
                        },
                        url:"course/coupon/send",
                    },
                    function (index,data) {

                        Fast.api.close(data.msg);
                        //成功的回调
                    },function () {
                        //失败的回调
                    }
                );
                // $("form", layero).submit();
            };
            //确认处理
            $("#dispose111").click(function () {
                var checkedbox= $("#table").bootstrapTable('getSelections'); 	//获取选中的数据
                var coupon_id = $("#coupon_id").val();
                var url = "course/coupon/send";
                Controller.api.bindevent();
                Fast.api.ajax({
                        url:url,
                        data:{coupon_id:coupon_id,checkedbox:checkedbox}
                    },
                    function () {
                        Fast.api.close("发送成功");
                        //成功的回调
                    },function () {
                        //失败的回调
                    }
                );
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                $('input[type=radio][name=row\\[type\\]]').change(function () {
                    var value = $(this).val();
                    if(value == "pay"){
                        $(".store_from_type").show(200);
                    } else {
                        $(".store_from_type").hide(200);
                    }
                });
            },
            formatter: {//渲染的方法
                info: function (value, row, index) {
                    var  msg = "";
                    if(row.type == "pay"){
                        msg += "价格" + row.coupon_money +"<br/>";
                    }
                    msg += "满" + row.money + "减" + row.reduction_money + "元";
                    return '<div>' +
                        '名称:' + value +'<br/>' + msg + "<br/>有效期：" + row.day + "天"+
                        '</div>';
                },

            },
        }
    };
    return Controller;
});